package com.hibernate.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.math.BigInteger;
import java.util.List;

/**
 * Created by francis on 2016/12/4.
 */

/**
 * Created by liwei.b on 2016/11/28.
 */
public class BaseDao extends HibernateDaoSupport {
    public <T> List<T> getAll(Class<T> tClass) {
        String lsql = "from " + getClassNameByClassFullPath(tClass);
        Query query = HibernateSessionFactory.getSession().createQuery(lsql);
        return query.list();
    }

    public <T> boolean addList(List<T> values, Class<T> tClass) {
        boolean flag = false;
        Transaction tx = null;
        Session session = null;
        try {
            session = HibernateSessionFactory.getSession();
            tx = session.beginTransaction();
            for (Object o : values) {
                session.save(o);
            }
            tx.commit();
            flag = true;
        } catch (Exception ex) {
            ex.printStackTrace();
            if (tx != null) {
                tx.rollback();
            }
        }
        return flag;
    }

    private String getClassNameByClassFullPath(Class tClass) {
        if (tClass == null) {
            return "";
        }
        String[] strClassNames = tClass.getName().split("\\.");
        return strClassNames[strClassNames.length - 1];
    }
}